<template>
	<div class="incpuser-form">
		<a-modal
			:title="handleType === 'set' ? '设置场内CP管理员' : ''"
			:visible="visible"
			:confirm-loading="confirmLoading"
			@ok="handleOk"
			@cancel="handleCancel"
		>
			<a-form-model
				ref="incpuserForm"
				:model="form"
				:rules="rules"
				v-bind="layout"
			>
				<!-- <a-form-model-item label="所属市场">
					<a-select
						v-model="form.market_id"
						style="width: 120px"
						@change="handleMarketChange"
					>
						<a-select-option
							v-for="(item, index) in form.marketData"
							:key="index"
							:value="item.id"
						>
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-model-item>
				<a-form-model-item label="场内CP" has-feedback>
					<a-select
						v-model="form.incp_id"
						style="width: 120px"
						@change="handleIncpChange"
					>
						<a-select-option
							v-for="(item, index) in form.incpData"
							:key="index"
							:value="item.id"
						>
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-model-item> -->

				<a-form-model-item label="手机号码" prop="phone" has-feedback>
					<a-input v-model="form.phone" placeholder="请输入" />
				</a-form-model-item>

				<a-form-model-item label="管理员" prop="username" has-feedback>
					<a-input v-model="form.username" placeholder="请输入" />
				</a-form-model-item>

				<!-- <a-form-model-item label="头像" prop="avatar" has-feedback>
					<div class="upload-file">
						<div class="avatar-wrapper" v-if="form.avatar">
							<img ref="img" class="avatar" :src="form.avatar" alt="" />
							<span class="delete-icon" @click="removeFile()"
								><img src="@/assets/images/ico_feedback_delete@2x.png" alt=""
							/></span>
						</div>
						<a
							href="javascript:void(0)"
							class="upload-icon"
							v-if="!form.avatar"
						>
							<span class="iconfont icon-xiangji"></span>
							<input
								type="file"
								accept="image/*"
								capture="camera"
								id="file"
								name="file"
								@change="uploadFile"
							/>
						</a>
					</div>
				</a-form-model-item> -->

				<!-- <a-form-model-item label="角色" prop="role_code" has-feedback>
					<app-select
						v-model="form.role_code"
						:code="$e.role"
						radio
						style="width: 100%"
						@change="(data) => (form.role_name = data.area_name_all)"
					/>
				</a-form-model-item> -->
				<a-form-model-item label="状态" has-feedback>
					<a-select
						v-model="form.status"
						style="width: 120px"
						placeholder="请选择"
						@changeStatus="changeStatus(item.key)"
						allowClear
					>
						<a-select-option
							v-for="(item, index) in statusList"
							:key="index"
							:value="item.key"
						>
							{{ item.text }}
						</a-select-option>
					</a-select>
				</a-form-model-item>
			</a-form-model>
		</a-modal>
	</div>
</template>

<script>
	// import User from "@/api/user"
	import moment from "moment"
	// import momentUtil from "@/utils/day"
	// import Incp from "@/api/incp"
	import IncpUser from "@/api/incpuser"
	import Incp from "@/api/incp"
	import salemarket from "@/api/salemarket"
	const lodash = require("lodash")

	export default {
		name: "HandleForm",
		data() {
			this.id = null
			this.handleType = null
			this.statusList = [
				{
					key: 1,
					text: "正常",
				},
				{
					key: 0,
					text: "停用",
				},
				{
					key: -1,
					text: "冻结",
				},
			]
			return {
				// show: false,
				// avatar: null,

				value1: null,
				value2: null,

				title: "增加",
				layout: {
					labelCol: { span: 6 },
					wrapperCol: { span: 12 },
				},
				ModalText: "Content of the modal",
				visible: false,
				confirmLoading: false,
				form: {
					id: "",
					// 必填
					incp_id: "",
					phone: undefined,
					username: undefined,
					// 选填
					avatar: "",
					// created_at: "",
					// incp_name: "",
					market_id: "",
					// market_name: "",
					status: undefined,
					marketData: [],
					incpData: [],
					// updated_at: "",
				},

				rules: {
					// market_id: [
					// 	{ required: true, trigger: "change", message: "市场ID必填" },
					// ],
					// incp_id: [
					// 	{ required: true, trigger: "change", message: "场内CPID必填" },
					// ],
					phone: [{ required: true, trigger: "change", message: "手机号必填" }],
					username: [
						{ required: true, trigger: "change", message: "用户名必填" },
					],
				},
			}
		},

		watch: {
			visible(newVal) {
				if (newVal == false) {
					this.resetFormFields()
				} else {
					// 获取批发市场列表
					this.getMarketData()
				}
			},
		},
		methods: {
			removeFile() {
				this.form.avatar = ""
				// this.show = false
			},
			uploadFile(e) {
				var event = e || window.event
				var target = event.target || e.srcElement
				var file = target.files[0]
				var formdata = new FormData()
				formdata.append("imgfile", file)
				var url = "http://127.0.0.1:9999/uploadimg"
				fetch(url, {
					// 设定请求方法
					method: "POST",
					headers: {
						// "content-type": "application/json",
					},
					body: formdata,
					// 设定传送的内容
					// body: JSON.stringify({
					// 	userName: "xxf",
					// 	userPwd: "123456",
					// }),
				})
					.then(function (response) {
						// 提取响应对象中的json格式数据
						// 通过response.code == 0判断
						console.log(response)
						return response.text()
					})

					.then((text) => {
						// 管道函数, 接收上一个函数返回的内容
						console.log(JSON.parse(text))
						this.form.avatar = JSON.parse(text).url
					})
					.catch(function (error) {
						// 网络出错或者禁止访问, 404/500无法找到资源不会报错
						console.log(error)
					})
				// this.show = true
			},
			moment,
			handleMarketChange(value) {
				console.log(`selected ${value}`)
				this.form.incp_id = ""
				this.form.market_id = value
				// 获取市场下场内CP列表
				this.getIncp(value)
			},

			handleIncpChange(value) {
				// console.log(value)
				this.form.incp_id = value
			},
			getIncp(market_id = "") {
				console.log(market_id)
				Incp.query({
					market_id,
				})
					.then((res) => {
						console.log(res)
						// this.loading = false
						if (res.code != 1) return
						this.form.incpData = []
						this.form.incpData = res.data.map((item) => {
							return {
								id: item.id,
								name: item.name,
							}
						})

						// this.pagination.total = res.page.totalSize
						// this.pagination.totalPage = res.page.totalPage
						//dataSource 默认将每列数据的 key 属性作为唯一的标识
						//处理数据，否则需要excel代码里处理了
						// this.data = res.data.map((item, index) => {
						// 	return Object.assign(item, { index: index + 1 })
						// })
						// ========================
						// if (this.data.length === 0) {
						// 	this.data = [
						// 		{ id: "1", name: "a" },
						// 		{ id: "2", name: "b" },
						// 	]
						// }
						// ========================
						// console.log(this.data)
					})
					.catch((e) => {
						// this.loading = false
					})
			},
			async getMarketData(params = {}) {
				this.form.marketData = []
				await salemarket.query(params).then((response) => {
					console.log("市场列表数据", response)
					if (response.code !== 1) {
						this.$message.warning(response.message)
						return
					}

					if (response.data && response.data.length > 0) {
						this.form.marketData = response.data.map((item) => {
							return {
								id: item.id,
								name: item.name,
							}
						})
					}
				})
			},
			// onChangeCreatedTime(time, timeString) {
			// 	// this.form.start_time = timeString
			// 	console.log(time, timeString)
			// 	// this.value1 = time
			// },
			onChangeEndTime(time, timeString) {
				this.form.end_time = timeString
				// console.log(time, timeString)
				this.value2 = time
			},
			formatStamp(timeStr) {
				console.log(
					timeStr,
					this.moment(this.$formatDate("h:m", +new Date(timeStr)), "HH:mm")
				)
				return this.moment(this.$formatDate("h:m", +new Date(timeStr)), "HH:mm")
			},
			getObj(rulesKeyArr) {
				let obj = {}
				for (let key of rulesKeyArr) {
					obj[key] = this.form[key]
				}
				return obj
			},
			checkRequire(obj) {
				return this.$isEmpty(obj)
			},

			changeStatus(value) {
				this.form.status = value
			},

			resetFormFields() {
				this.form = {
					id: "",

					// 必填
					incp_id: "",
					phone: undefined,
					username: undefined,
					// 选填
					avatar: "",
					// created_at: "",
					// incp_name: "",
					market_id: "",
					// market_name: "",
					status: undefined,
					marketData: [],
					incpData: [],
					role_code: "",
					// updated_at: "",
				}
				this.value1 = null
				this.value2 = null
				// this.show = false
				this.$refs.incpuserForm.resetFields()
			},

			handleOk() {
				// this.handleType === "set" ? this.addIncpUser() : this.updateIncpUser()
				if (this.form.id === "" || this.form.id == 0) {
					this.addIncpUser()
				} else {
					this.updateIncpUser()
				}
				// this.handleType === "set" ? this.addIncpUser() : ""
			},
			addIncpUser() {
				let _this = this

				// _this.form.created_at._d = this.$standardDateToTimstamp(
				// 	_this.form.created_at._d
				// )

				// _this.form.updated_at._d = this.$standardDateToTimstamp(
				// 	_this.form.updated_at._d
				// )
				_this.$refs.incpuserForm.validate((err, values) => {
					// 验证表单没错误
					if (err) {
						_this.confirmLoading = true
						IncpUser.create(
							this.$removeField(
								// ..._this.form,
								lodash.omit(_this.form, ["marketData", "incpData", "id"])
								// created_at: this.$standardDateToTimstamp(
								// 	_this.form.created_at._d
								// ),
								// updated_at: this.$standardDateToTimstamp(
								// 	_this.form.updated_at._d
								// ),
							)
						)
							.then((res) => {
								_this.confirmLoading = false
								if (res.code == 1) {
									_this.$message.success("添加成功")
									_this.$emit("handleOk")
									setTimeout(() => {
										_this.visible = false
									}, 500)
								}
							})
							.catch((e) => {
								_this.confirmLoading = false
							})
					}
				})
			},

			updateIncpUser() {
				let _this = this
				_this.$refs.incpuserForm.validate((err, values) => {
					// 验证表单没错误
					if (err) {
						_this.confirmLoading = true
						IncpUser.update(
							_this.form.id,
							this.$removeField(
								lodash.omit(_this.form, ["marketData", "incpData"])
							)
						)
							.then((res) => {
								_this.confirmLoading = false
								if (res.code == 1) {
									_this.$message.success("修改成功")
									_this.$emit("handleOk")
									setTimeout(() => {
										_this.visible = false
									}, 500)
								}
							})
							.catch((e) => {
								_this.confirmLoading = false
							})
					}
				})
			},
			// getIncpDetail(id) {
			// 	IncpUser.select(id).then((res) => {
			// 		console.log("场内cp详情", res)
			// 		// if (res.code == 1) {
			// 		// }
			// 	})
			// },
			showModal(type, record) {
				console.log(type, record)
				this.handleType = type
				// if (type === "update") {
				// 	this.form = {
				// 		role_code: record.role_code,
				// 		id: record.id,
				// 		avatar: record.avatar,
				// 		incp_id: record.incp_id,
				// 		market_id: record.market_id,
				// 		phone: record.phone,
				// 		username: record.username,
				// 		status: record.status,
				// 		marketData: [],
				// 		incpData: [],
				// 	}
				// 	// this.show = true

				// 	this.getMarketData()
				// 	this.getIncp(record.market_id)
				// } else if (type === "add") {

				// } else
				if (type === "set") {
					if (record) {
						this.form = {
							// role_code: record.role_code,
							// id: record.id,
							// avatar: record.avatar,
							incp_id: record.id,
							// map_area_id: record.map_area_id,
							admin_role: true,
							market_id: record.market_id,
							role_code: "0001",
							role_name: "管理员",

							username: record.admin_user,
							id: record.admin_user_id,
							phone: record.phone,
							status: record.admin_user_status,
							// phone: record.phone,
							// username: record.username,
							// status: record.status,
							// marketData: [],
							// incpData: [],
						}
					}
				}
				this.visible = true
			},

			handleCancel(e) {
				this.visible = false
			},
		},
	}
</script>

<style lang='less' scoped>
	// .incpuser-form {
	.upload-file {
		margin-left: 5px;
		.avatar-wrapper {
			width: 100px;
			height: 100px;
			position: relative;
			.avatar {
				width: 100%;
				height: 100%;
			}
			.delete-icon {
				position: absolute;
				right: -8px;
				top: -8px;
				width: 18px;
				height: 18px;
				line-height: 18px;
				text-align: center;
				cursor: pointer;
				img {
					width: 100%;
					height: 100%;
				}
			}
		}
		.upload-icon {
			border: 1px solid rgba(0, 0, 0, 0.2);
			position: relative;
			left: 0;
			display: inline-block;
			color: #fff;
			text-decoration: none;
			width: 100px;
			height: 100px;
			line-height: 100px;
			text-align: center;
			.icon-xiangji {
				font-size: 28px;
				color: #333;
				margin-right: 0;
			}
			#file {
				opacity: 0;
				width: 100%;
				height: 100%;
				position: absolute;
				left: 0;
				top: 0;
			}
		}
	}
	// }
</style>
